package com.example.music.fragment;

import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.SearchView;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.music.R;
import com.example.music.activity.CategoryDetailActivity;
import com.example.music.adapter.CategoryAdapter;
import com.example.music.model.CategoryItem;
import com.example.music.model.Song;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class CategoryFragment extends Fragment {
    private static final String TAG = "CategoryFragment";
    private RecyclerView recyclerView;
    private CategoryAdapter adapter;
    private List<CategoryItem> categoryList = new ArrayList<>();

    // 分类类型枚举
    public enum CategoryType { BY_SINGLE, BY_ALBUM, BY_ARTIST, BY_FOLDER }

    public static CategoryFragment newInstance(CategoryType type) {
        CategoryFragment fragment = new CategoryFragment();
        Bundle args = new Bundle();
        args.putSerializable("category_type", type);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_category, container, false);
        recyclerView = view.findViewById(R.id.recycler_view);
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));

        // 加载分类数据
        loadCategoryData();

        // 搜索功能
        SearchView searchView = view.findViewById(R.id.search_view);
        if (searchView != null) {
            searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
                @Override
                public boolean onQueryTextSubmit(String query) {
                    return false;
                }

                @Override
                public boolean onQueryTextChange(String newText) {
                    filterCategories(newText);
                    return true;
                }
            });
        } else {
            Log.e(TAG, "SearchView not found in the layout");
        }

        return view;
    }

    private void loadCategoryData() {
        CategoryType type = (CategoryType) getArguments().getSerializable("category_type");
        Map<String, List<Song>> categoryMap = new HashMap<>();

        // 从媒体库读取歌曲并分类
        try (Cursor cursor = requireContext().getContentResolver().query(
                MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
                new String[]{
                        MediaStore.Audio.Media.TITLE,
                        MediaStore.Audio.Media.ARTIST,
                        MediaStore.Audio.Media.ALBUM,
                        MediaStore.Audio.Media.DATA
                },
                MediaStore.Audio.Media.IS_MUSIC + " != 0",
                null,
                null
        )) {
            if (cursor == null) {
                Log.e(TAG, "Failed to get cursor");
                return;
            }

            while (cursor.moveToNext()) {
                Song song = new Song(
                        cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.TITLE)),
                        cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ARTIST)),
                        cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM)),
                        cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA))
                );

                String key = getCategoryKey(type, song);
                if (!categoryMap.containsKey(key)) {
                    categoryMap.put(key, new ArrayList<>());
                }
                categoryMap.get(key).add(song);
            }
        } catch (Exception e) {
            Log.e(TAG, "Error loading songs", e);
        }

        // 转换为列表
        for (Map.Entry<String, List<Song>> entry : categoryMap.entrySet()) {
            categoryList.add(new CategoryItem(entry.getKey(), entry.getValue().size()));
        }

        // 设置Adapter
        adapter = new CategoryAdapter(categoryList, item -> {
            // 跳转到二级界面
            Intent intent = new Intent(getActivity(), CategoryDetailActivity.class);
            intent.putExtra("category_type", type.name());
            intent.putExtra("category_name", item.getName());
            startActivity(intent);
        });
        recyclerView.setAdapter(adapter);
    }

    private String getCategoryKey(CategoryType type, Song song) {
        switch (type) {
            case BY_SINGLE:
                return song.getTitle(); // 单曲按歌曲名分类
            case BY_ALBUM:
                return song.getAlbum();
            case BY_ARTIST:
                return song.getArtist();
            case BY_FOLDER:
                File file = new File(song.getPath());
                return file.getParent();
            default:
                return "";
        }
    }

    private void filterCategories(String query) {
        adapter.getFilter(query);
    }
}